#!/usr/bin/env python3
import os
from PIL import Image

def crop_avatars():
    source_image_path = "/home/ubuntu/MBTI_Qt_App_Package/mbti_avatars/all_avatars.jpg"
    output_dir = "/home/ubuntu/MBTI_Qt_App_Package/mbti_avatars/"

    # Ensure output directory exists
    os.makedirs(output_dir, exist_ok=True)

    # MBTI types in the order they appear in the image (4x4 grid)
    # Row 1: INTJ, INTP, ENTJ, ENTP
    # Row 2: INFJ, INFP, ENFJ, ENFP
    # Row 3: ISTP, ISFP, ESTP, ESFP
    # Row 4: ISTJ, ISFJ, ESTJ, ESFJ
    types_in_order = [
        "INTJ", "INTP", "ENTJ", "ENTP",
        "INFJ", "INFP", "ENFJ", "ENFP",
        "ISTP", "ISFP", "ESTP", "ESFP",
        "ISTJ", "ISFJ", "ESTJ", "ESFJ"
    ]

    try:
        img = Image.open(source_image_path)
        img_width, img_height = img.size
        print(f"Source image dimensions: {img_width}x{img_height}")

        # Assuming a 4x4 grid of avatars
        cols = 4
        rows = 4
        avatar_width = img_width // cols
        avatar_height = img_height // rows

        print(f"Calculated avatar cell dimensions: {avatar_width}x{avatar_height}")

        # Define a slight padding/margin to cut from each side of the calculated cell
        # This is to avoid cutting into adjacent avatars if there's no spacing
        # and to center the crop if the avatars are smaller than the cell.
        # These values might need adjustment based on the actual image layout.
        horizontal_padding_percent = 0.10 # 10% padding from left/right of the cell
        vertical_padding_percent = 0.05   # 5% padding from top/bottom of the cell

        crop_margin_x = int(avatar_width * horizontal_padding_percent)
        crop_margin_y = int(avatar_height * vertical_padding_percent)

        for i, mbti_type in enumerate(types_in_order):
            row = i // cols
            col = i % cols

            # Calculate initial bounding box for the cell
            left = col * avatar_width
            top = row * avatar_height
            right = left + avatar_width
            bottom = top + avatar_height

            # Adjust for padding to get the actual crop box
            crop_left = left + crop_margin_x
            crop_top = top + crop_margin_y
            crop_right = right - crop_margin_x
            crop_bottom = bottom - crop_margin_y
            
            # Ensure crop dimensions are valid
            if crop_left >= crop_right or crop_top >= crop_bottom:
                print(f"Warning: Invalid crop dimensions for {mbti_type}. Using cell dimensions.")
                cropped_avatar = img.crop((left, top, right, bottom))
            else:
                cropped_avatar = img.crop((crop_left, crop_top, crop_right, crop_bottom))
            
            output_path = os.path.join(output_dir, f"{mbti_type}.png")
            cropped_avatar.save(output_path)
            print(f"Saved {mbti_type}.png (cropped from box: ({crop_left},{crop_top},{crop_right},{crop_bottom}))")

        print("Successfully cropped and saved all 16 avatars.")

    except FileNotFoundError:
        print(f"Error: Source image not found at {source_image_path}")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    crop_avatars()

